package access.spg.android.com.accessibilitytest

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.graphics.Path
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.accessibilityservice.GestureDescription
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.support.annotation.RequiresApi


class AutoPunchCardService : AccessibilityService(){

    private val tag = "AutoPunchCardService"

    //可选。系统会在成功连接上你的服务的时候调用这个方法，在这个方法里你可以做一下初始化工作，
    //例如设备的声音震动管理，也可以调用setServiceInfo()进行配置工作
    override fun onServiceConnected() {
        super.onServiceConnected()
        Log.d(tag,"onServiceConnected")
    }

    //必须。这个在系统想要中断AccessibilityService返给的响应时会调用。在整个生命周期里会被调用多次。
    override fun onInterrupt() {
        Log.d(tag,"onInterrupt")
    }



    //可选。在系统将要关闭这个AccessibilityService会被调用。在这个方法中进行一些释放资源的工作
    override fun onUnbind(intent: Intent?): Boolean {
        Log.d(tag,"onUnbind")
        return super.onUnbind(intent)
    }


    //通过这个函数可以接收系统发送来的AccessibilityEvent，
    //接收来的AccessibilityEvent是经过过滤的，过滤是在配置工作时设置的。
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        Log.d(tag,"事件--> $event.eventType ,app包名--> $event.packageName")
        when (event.eventType) {
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED  //收到通知栏消息
                    -> Log.d(tag,"=== 收到通知栏消息")
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED    //界面状态改变
                    -> Log.d(tag,"=== 界面状态改变，" + event.toString())
            AccessibilityEvent.TYPE_VIEW_CLICKED   //点击事件
                    ->  Log.d(tag,"=== 点击事件" + event.toString())
            AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT //文本改变
                    -> Log.d(tag,"=== 文本改变")
            AccessibilityEvent.TYPE_VIEW_SCROLLED//滑动下一页
                    ->scrollUp()
        }//省略其他的一堆可以监听的事件

    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun scrollUp(): Boolean {
        Log.d(tag,"================滑动================" )
        try {//滞留
            Thread.sleep(3000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        val builder = GestureDescription.Builder()
        val path = Path()
        val y1 = MyUtil.getWindowHeight(this)*0.8f
        val y2 = MyUtil.getWindowHeight(this)*0.4f
        val x =MyUtil.getWindowWidth(this)/2f
        Log.d(tag,"x======="+x )
        Log.d(tag,"y1======"+y1 )
        Log.d(tag,"y2======"+y2 )
        path.moveTo(x, y1)
        path.lineTo(x, y2)


        val gestureDescription = builder.addStroke(GestureDescription.StrokeDescription(path, 500, 800,false)).build()

        dispatchGesture(gestureDescription, object: GestureResultCallback() {
            override fun onCompleted(gestureDescription: GestureDescription?) {
                super.onCompleted(gestureDescription)
                Log.e(tag, "============onCompleted===============" )
            }

            override fun onCancelled(gestureDescription: GestureDescription?) {
                Log.e(tag, "============onCancelled===============" )
            }
        },Handler(Looper.getMainLooper()))



        return true
    }




    private fun click(viewText: String): Boolean {
        val nodeInfo = rootInActiveWindow
        try {//点击前滞留1s
            Thread.sleep(1000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        if (nodeInfo == null) {
            Log.d(tag,"点击失败，rootWindow为空")
            return false
        }

        val list = nodeInfo.findAccessibilityNodeInfosByText(viewText)
        if (list.isEmpty()) {//没有该文字的控件
            Log.d(tag,"点击失败，" + viewText + "控件列表为空")
            return false
        } else {
            for (info in list) {
                if (viewText == info?.text?.toString()) {
                    return onclick(info)  //遍历点击
                }
            }
            return false
        }
    }

    private fun onclick(view: AccessibilityNodeInfo): Boolean {
        if (view == null) {
            Log.d(tag,"node 为空无法点击")
            return false
        }
        if (view.isClickable) {
            view.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Log.d(tag,"view name" + view.className + "+点击成功")
            return true
        } else {
            if (view.parent == null) {
                return false
            }
            return onclick(view.parent)
        }
    }





}